# -*- coding: utf-8 -*-
from django.db.models import permalink

from google.appengine.ext import db
from google.appengine.ext.db import *
from ragendja.auth.models import *
from datetime import datetime
import sys
from metaweb import get_bvr_type
from django.db.models.signals import pre_delete
from ragendja.dbutils import cleanup_relations

###############################################
# The main user model.
class User(User):
    # Areas of expertise
    personal_statement = db.TextProperty(required=False)  
    # Technologies that the user is an expert in
    #medical_condition_expertise = db.StringListProperty(required=False) # Medical conditions that the user is an expert in
    # user basics (seem to be working)
    score = db.FloatProperty()
    mt_edits = db.IntegerProperty()
    home_page = db.StringProperty()
    user_image = db.BlobProperty(default=None)
    
#class bvr_user(db.Model):
    ## these things come from django User model now
    #login_uid = db.StringProperty(required=True)    # The user's unique identifier
    # Personal information
    #first_name = db.StringProperty()                # The user's first name
    #last_name = db.StringProperty()                 # The user's last name
    
 
    def __unicode__(self):
        return self.username
 
 #logs and stores user edits
 
    def store_edit(self, result, type='upload', verbose=None):
        
        user = self
        if (verbose) : 
            logging.info('result :' + repr(result)+'\n')

        if user.is_authenticated():
            #add the edit dependent on type:
            if(type=='link'):
                edit = freebase_edit(user = user, raw_json = result.content)
            elif(type=='unlink'):
                edit = freebase_edit(user = user, raw_json = result.content)
            elif(type=='create'):
                edit = freebase_edit(user = user, raw_json = result.content)
            elif(type=='upload'):
                edit = freebase_edit(user = user, raw_json = result.content)
            if(type=='primitive'):
                edit = freebase_edit(user = user, raw_json = result.content)
            edit.put()    
            if user.mt_edits > -1:
                user.mt_edits += 1
            else:
                user.mt_edits = 0
            user.save()               
            return True
        else:
            sys.stderr.write( "\n\n not authenticated \n\n"  )
            return False

    def store_edit_full(self, write_result, read_result, read_options, type, verbose):
        print "mishu"
        user = self
        if (verbose) : 
            logging.info('store_edit_full - write_result :' + repr(write_result)+'\n')
            logging.info('store_edit_full - read_result :' + repr(read_result)+'\n')
            logging.info('store_edit_full - read_options :' + repr(read_options)+'\n')

        if user.is_authenticated():
            #add the edit dependent on type:
            if(type=='link'):
                topic1_property = read_options["topic1_property"]
                topic1_id = read_result["id"]
                topic1_name = read_result["name"]
                topic1_bvr_type = get_bvr_type(read_result['type'])
                
                topic2_result = read_result[topic1_property]
                topic2_id = topic2_result['id']
                topic2_name = topic2_result['name']
                topic2_bvr_type = get_bvr_type(topic2_result['type'])

                timestamp = topic2_result['link']['timestamp']
                timestamp = timestamp.rsplit(".")[0] 
                timestamp = datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S")
                
                edit = freebase_edit_link(
                                       user = user, 
                                       raw_json = write_result.content,
                                       topic1_property = topic1_property,
                                       topic1_id = topic1_id,
                                       topic1_name = topic1_name,
                                       topic1_bvr_type = topic1_bvr_type,
                                       topic2_id = topic2_id,
                                       topic2_name = topic2_name,
                                       topic2_bvr_type = topic2_bvr_type,
                                       timestamp = timestamp
                                       )

            elif(type=='unlink'):
                edit = freebase_edit(user = user, raw_json = write_result.content)
            elif(type=='create'):
                edit = freebase_edit(user = user, raw_json = write_result.content)
            elif(type=='upload'):
                edit = freebase_edit(user = user, raw_json = write_result.content)
            if(type=='primitive'):
                edit = freebase_edit(user = user, raw_json = write_result.content)
            edit.put()    
            if user.mt_edits > -1:
                user.mt_edits += 1
            else:
                user.mt_edits = 0
            user.save()               
            return True
        else:
            sys.stderr.write( "\n\n not authenticated \n\n"  )
            return False
    
    # Freebase edits:
    # To fetch and iterate over every SecondModel entity that refers to the
    # for f_edit in user.freebase_edit_set:
    # ...   
###############################################
# Freebase edit models.

# The parent class    
class freebase_edit(polymodel.PolyModel):
    #here we link these to the User model
    user = db.ReferenceProperty(User, required=True)
    raw_json = db.StringProperty(multiline=True)
    timestamp = db.DateTimeProperty()
    
# For topics that are linked
class freebase_edit_link(freebase_edit):
    topic1_property = db.StringProperty()#(required=True)
    topic1_id = db.StringProperty()#(required=True)
    topic1_name = db.StringProperty()
    topic1_bvr_type = db.StringProperty()
    topic2_id = db.StringProperty()#(required=True)
    topic2_name = db.StringProperty()
    topic2_bvr_type = db.StringProperty()
    

# For newly created topics
class freebase_edit_create(freebase_edit):
    topic_types = db.StringListProperty()    


pre_delete.connect(cleanup_relations, sender=User)